package com.jixiang.tracedata.config;

import com.ibm.mq.jms.MQQueueConnectionFactory;
import com.ibm.msg.client.wmq.WMQConstants;
import com.jixiang.tracedata.ibmmq.IbmMqListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.SimpleMessageListenerContainer;

import javax.annotation.Resource;
import javax.jms.MessageListener;
import java.util.concurrent.ExecutorService;

/**
 * @author quanbiao
 * @date 2018-09-10
 */
@Configuration
public class JmsConfig {

    @Value("${project.mq.host}")
    private String host;

    @Value("${project.mq.port}")
    private Integer port;

    @Value("${project.mq.queue-manager}")
    private String queueManager;

    @Value("${project.mq.channel}")
    private String channel;

    @Value("${project.mq.queue}")
    private String queue;

    @Value("${project.mq.receive-timeout}")
    private long receiveTimeout;

    @Autowired
    private IbmMqListener ibmMqListener;

    @Resource(name = "asyncJmsReceive")
    private ExecutorService executorService;

    @Bean
    @Primary
    public MQQueueConnectionFactory mqQueueConnectionFactory() {
        MQQueueConnectionFactory mqQueueConnectionFactory = new MQQueueConnectionFactory();
        try {
            mqQueueConnectionFactory.setHostName(host);
            mqQueueConnectionFactory.setQueueManager(queueManager);
            mqQueueConnectionFactory.setPort(port);
            mqQueueConnectionFactory.setChannel(channel);
            mqQueueConnectionFactory.setAppName("trace-data");
            mqQueueConnectionFactory.setTransportType(WMQConstants.WMQ_CM_CLIENT);
            mqQueueConnectionFactory.setCCSID(1208);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mqQueueConnectionFactory;
    }

    @Bean
    public SimpleMessageListenerContainer queueContainer(MQQueueConnectionFactory mqQueueConnectionFactory) {
        MessageListener listener = ibmMqListener;
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(mqQueueConnectionFactory);
        container.setDestinationName(queue);
        container.setConcurrentConsumers(2);
        container.setTaskExecutor(executorService);
        container.setMessageListener(listener);
        container.start();
        return container;
    }

    @Bean
    public JmsTemplate queueTemplate(MQQueueConnectionFactory mqQueueConnectionFactory) {
        JmsTemplate jmsTemplate = new JmsTemplate(mqQueueConnectionFactory);
        jmsTemplate.setReceiveTimeout(receiveTimeout);
        return jmsTemplate;
    }

}
